<template>
	<view class="container">
		<view class="stat-cards">
			<view class="stat-card green">
				<view class="card-section">
					<text>商品总量</text>
					<text>{{ stats.total }}</text>
				</view>
				<view class="divider"></view>
				<view class="card-section">
					<text>普通商品 {{ stats.regular }} 件</text>
					<text>服务商品 {{ stats.service }} 件</text>
				</view>
			</view>
			<view class="stat-card blue">
				<view class="card-section">
					<text>库存预警</text>
					<text>{{ stats.lowStock }} 件</text>
				</view>
				<view class="divider"></view>
				<view class="card-section">
					<text>库存不足5件--共 {{ stats.stockBelow5 }} 件</text>
					<text>库存不足10件--共 {{ stats.stockBelow10 }} 件</text>
					<text>库存不足15件--共 {{ stats.stockBelow15 }} 件</text>
				</view>
			</view>
		</view>

		<!-- 搜索和操作按钮区域 -->
		<view class="controls">
			<!-- 搜索框 -->
			<uni-search-bar v-model="searchQuery" placeholder="输入产品名称" class="search-bar"></uni-search-bar>
			<view class="control-buttons">
				<button class="control-button" size="mini" @click="fetchProducts">搜索产品</button>
			</view>

			<!-- 操作按钮 -->
			<view class="control-buttons">
				<button class="control-button" size="mini" @click="openAddPopup">新增产品</button>
			</view>
		</view>

		<!-- 产品列表表格 -->
		<uni-table>
			<uni-tr>
				<uni-th align="center">商品编号</uni-th>
				<uni-th align="center">商品名称</uni-th>
				<uni-th align="center">商品简码</uni-th>
				<uni-th align="center">零售价格</uni-th>
				<uni-th align="center">商品类型</uni-th>
				<uni-th align="center">商品分类</uni-th>
				<uni-th align="center">会员特价</uni-th>
				<uni-th align="center">仓库库存</uni-th>
				<uni-th align="center">门店库存</uni-th>
				<uni-th align="center">单位</uni-th>
				<uni-th align="center">操作</uni-th>
			</uni-tr>

			<uni-tr v-for="(product, index) in filteredProducts" :key="index">
				<uni-td align="center">{{ product.product_code }}</uni-td>
				<uni-td align="center">{{ product.product_name }}</uni-td>
				<uni-td align="center">{{ product.short_code }}</uni-td>
				<uni-td align="center">{{ product.retail_price }}</uni-td>
				<uni-td align="center">
					<view v-if="product.product_type == 1">
						普通商品
					</view>
					<view v-else>服务商品</view>
				</uni-td>
				<uni-td align="center">{{ getCategoryName(product.category_id) }}</uni-td>
				<uni-td align="center">{{ product.member_discount }}</uni-td>
				<uni-td align="center">{{ product.total_quantity }}</uni-td>
				<uni-td align="center">{{ product.shop_stock }}</uni-td>

				<uni-td align="center">{{ getUnitName(product.unit) }}</uni-td>
				<uni-td align="center">
					<button class="button" type="primary" @click="openEdit(product)" size="mini">编辑</button>
					<!-- <button class="button" type="warn" @click="confirmDelete(product)" size="mini"
						style="margin-left: 5px;">删除</button> -->
					<button class="button" type="default" size="mini" @click="viewSpecsStock(product)"
						style="margin-left: 5px;margin-right: 5px;">规格库存</button>

					<button class="button" type="primary" size="mini" @click="openTransferPopup(product)">调货</button>
				</uni-td>
			</uni-tr>
		</uni-table>

		<!-- 分页组件 -->
		<view style="margin-top: 20px;">
			<!-- <uni-pagination :total="totalPages" @change="handlePageChange" /> -->
			<uni-pagination 
			:current="currentPage" 
			:total="totalRecords" 
			:page-size="pageSize"
			@change="handlePageChange"
			show-total
			show-elevator
			/>
		</view>

		<!-- 编辑商品弹窗 -->
		<uni-popup ref="editPopup" type="center">
			<view class="member-modal">
				<h3>编辑商品信息</h3>
				<!-- 表单输入字段 -->
				<view class="form-row">
					<label>商品编号：</label>
					<input v-model="currentProduct.product_code" class="input-field" />
				</view>
				<view class="form-row">
					<label>商品名称：</label>
					<input v-model="currentProduct.product_name" class="input-field"
						@input="generateShortCode(currentProduct)" />
				</view>
				<view class="form-row">
					<label>商品简码：</label>
					<input v-model="currentProduct.short_code" class="input-field" />
				</view>
				<view class="form-row">
					<label>零售价格：</label>
					<input v-model="currentProduct.retail_price" class="input-field" />
				</view>
				<view class="form-row">
					<view class="form-group" style="display: flex;">
						<label>商品类型：</label>
						<radio-group @change="radioChange" class="gender-options">
							<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in items"
								:key="item.value">
								<radio :value="item.value" :checked="index === current" />{{ item.name }}
							</label>
						</radio-group>
					</view>
				</view>
				<view class="form-row">
					<label>单位：</label>
					<select v-model="currentProduct.unit" class="input-field">
						<option value="" disabled>请选择单位</option>
						<option v-for="unit in unitPickerList" :key="unit.id" :value="unit.id">{{ unit.name }}</option>
					</select>
				</view>
				<view class="form-row">
					<label>会员特价：</label>
					<input v-model="currentProduct.member_discount" class="input-field" />
				</view>
				<!-- <view class="form-row">
					<label>商品分类：</label>
					<picker mode="selector" :range="categoryPickerList" range-key="label"
						v-model="currentProduct.category_id" class="input-field" @change="updateCurrentCategory">
						<view>{{ getCategoryName(currentProduct.category_id) || '请选择分类' }}</view>
					</picker>
				</view> -->
				<view class="form-row">
				<label>商品分类：</label>
				<picker mode="selector" 
						:range="categoryPickerList" 
						range-key="label"
						@change="updateNewCategory">
					<view>{{ getCategoryName(newProduct.category_id) || '请选择分类' }}</view>
				</picker>
				</view>
				<!-- 保存和取消按钮 -->
				<view class="button-group">
					<button class="modal-button save" @click="saveProduct" size="mini">保存</button>
					<button class="modal-button cancel" @click="closePopup" size="mini">取消</button>
				</view>
			</view>
		</uni-popup>

		<!-- 新增产品弹窗 -->
		<uni-popup ref="addPopup" type="center">
			<view class="member-modal">
				<h3>新增商品</h3>
				<!-- 表单输入字段 -->
				<view class="form-row">
					<label>商品编号：</label>
					<input v-model="newProduct.product_code" class="input-field" />
				</view>
				<view class="form-row">
					<label>商品名称：</label>
					<input v-model="newProduct.product_name" class="input-field"
						@input="generateShortCode(newProduct)" />
				</view>
				<view class="form-row">
					<label>商品简码：</label>
					<input v-model="newProduct.short_code" class="input-field" disabled
						style="background-color: lightgray;" />
				</view>
				<view class="form-row">
					<label>零售价格：</label>
					<input v-model="newProduct.retail_price" class="input-field" />
				</view>
				<view class="form-row">
					<view class="form-group" style="display: flex;">
						<label>商品类型：</label>
						<radio-group @change="radioChange" class="gender-options">
							<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in items"
								:key="item.value">
								<radio :value="item.value" :checked="index === current" />{{ item.name }}
							</label>
						</radio-group>
					</view>
				</view>
				<view class="form-row">
					<label>商品分类：</label>
					<picker mode="selector" :range="categoryPickerList" range-key="label"
						v-model="newProduct.category_id" class="input-field" @change="updateNewCategory">
						<view>{{ getCategoryName(newProduct.category_id) || '请选择分类' }}</view>
					</picker>
				</view>
				<view class="form-row">
					<label>单位：</label>
					<select v-model="newProduct.unit" class="input-field">
						<option value="" disabled>请选择单位</option>
						<option v-for="unit in unitPickerList" :key="unit.id" :value="unit.id">{{ unit.name }}</option>
					</select>
				</view>
				<!-- 保存和取消按钮 -->
				<view class="button-group">
					<button class="modal-button save" @click="addProduct" size="mini">添加</button>
					<button class="modal-button cancel" @click="closePopup" size="mini">取消</button>
				</view>
			</view>
		</uni-popup>

		<!-- 规格库存弹窗 -->

		<uni-popup ref="specsStockPopup" type="center">
			<uni-table>

				<uni-th align="center">规格名称</uni-th>
				<uni-th align="center">规格值</uni-th>
				<uni-th align="center">总库存</uni-th>
				<uni-th align="center">仓库库存</uni-th>
				<uni-th align="center">门店库存</uni-th>
				<uni-th align="center">零售价格</uni-th>
				<uni-th align="center">会员特价</uni-th>
				<!-- <uni-th align="center">操作</uni-th> -->
				<uni-tr v-for="spec in specsStock" :key="spec.id">
					<uni-td align="center">{{ spec.spec_name }}</uni-td>
					<uni-td align="center">{{ spec.spec_value }}</uni-td>
					<uni-td align="center">{{ spec.total_quantity }}</uni-td>
					<uni-td align="center">{{ spec.warehouse_quantity }}</uni-td>
					<uni-td align="center">{{ spec.store_quantity }}</uni-td>
					<uni-td align="center">{{ spec.retail_price }}</uni-td>
					<uni-td align="center">{{ spec.member_discount }}</uni-td>
					<!-- <uni-td align="center">
						<button class="button" type="primary" @click="editSpec(spec)" size="mini">编辑</button> 
					</uni-td> -->
				</uni-tr>
			</uni-table>
		</uni-popup>

		<!-- 替换后 -->
		<uni-popup ref="specsStockPopup" type="center">
			<view class="specs-table">
				<view class="table-header">
					<view class="header-cell">规格名称</view>
					<view class="header-cell">规格值</view>
					<view class="header-cell">总库存</view>
					<view class="header-cell">仓库库存</view>
					<view class="header-cell">门店库存</view>
					<view class="header-cell">零售价格</view>
					<view class="header-cell">会员特价</view>
					<!-- 其他表头 -->
				</view>
				<view class="table-body">
					<view class="table-row" v-for="spec in specsStock" :key="spec.id">
						<view class="table-cell">{{ spec.spec_name }}</view>
						<view class="table-cell">{{ spec.spec_value }}</view>
						<view class="table-cell">{{ spec.total_quantity }}</view>
						<view class="table-cell">{{ spec.warehouse_quantity }}</view>
						<view class="table-cell">{{ spec.store_quantity }}</view>
						<view class="table-cell">{{ spec.retail_price }}</view>
						<view class="table-cell">{{ spec.member_discount }}</view>
						<!-- 其他单元格 -->
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 调货弹窗 -->
		<uni-popup ref="transferPopup" type="center">
			<view class="popup-container">
				<h3>商品调货</h3>
				<view class="form-row">
					<label>调入门店：</label>
					<picker mode="selector" :range="storePickerList" range-key="name"
						@change="updateDestinationStoreId">
						<view class="picker">{{ getStoreName(currentTransfer.to_shop_id) || '选择门店' }}</view>
					</picker>
				</view>
				<view class="form-row">
					<label>选择规格：</label>
					<picker mode="selector" :range="specPickerList" range-key="spec_name" @change="updateSpecId"
          				:value="getDefaultSpecIndex()">
						<view class="picker">{{ getSpecName(currentTransfer.spec_id) || '选择规格' }}</view>
					</picker>
				</view>

				<view class="form-row">
					<label>调货数量：</label>
					<input v-model="currentTransfer.quantity" type="number" class="input-field" />
					<text style="margin-left: 10px; color: #666;">(最大可调: {{ currentTransfer.max_quantity }})</text>
				</view>
				<view class="button-group">
					<button class="modal-button save" @click="saveTransfer" size="mini">保存</button>
					<button class="modal-button cancel" @click="closePopup" size="mini">取消</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import pinyin from 'js-pinyin'; // 导入拼音转换库

export default {
	data() {
		return {
			warehouseStock: 0, // 添加仓库库存字段
			products: [], // 商品列表
			filteredProducts: [], // 筛选后的商品列表
			currentProduct: {}, // 当前编辑的商品
			newProduct: { // 新增的商品

				product_code: '',
				product_name: '',
				short_code: '',
				retail_price: '',
				product_type: '',
				member_discount: '',
				offline_cashier: '',
				operator: '',
				category_id: '', // 新增分类字段
				unit_id: '' // 新增单位字段
			},
			categories: [], // 分类列表
			categoryPickerList: [], // 分类选择列表
			units: [], // 单位列表
			unitPickerList: [], // 单位选择列表
			totalPages: 1, // 总页数
			currentPage: 1, // 当前页码
			searchQuery: '', // 搜索关键词
			userInfo: {}, // 用户信息
			mainAccountId: 0, // 主账号ID
			shopId: 0, // 门店ID
			stats: [], // 统计信息
			items: [{
				name: "普通",
				value: "1"
			},
			{
				name: "服务",
				value: "2"
			}
			],
			current: 0,
			currentTransfer: {
				product_id: '',
				from_shop_id: 0,
				to_shop_id: '',
				quantity: 0,
				spec_id: '' // 添加spec_id字段
			}, // 当前调货信息
			storePickerList: [], // 门店选择列表
			specPickerList: [], // 规格选择列表
			specsStock: [], // 规格库存信息
			currentPage: 1,      // 当前页码
			pageSize: 10,        // 每页条数（需与后端一致）
			totalRecords: 0,     // 总记录数
			totalPages: 1,       // 总页数
		};
	},
	methods: {

		// 打开查看规格库存弹窗
		async viewSpecsStock(product) {
			await this.fetchSpecsStock(product.id); // 获取规格库存信息
			this.$refs.specsStockPopup.open();
		},
		// 获取规格库存信息
		async fetchSpecsStock(productId) {
			const res = await this.$myRuquest({
				url: '/index/plugin.users/getSpecsStock',
				method: 'GET',
				data: {
					product_id: productId,
					main_account_id: this.mainAccountId,
				}
			});
			if (res.data.code === 200) {
				this.specsStock = res.data.data;
			} else {
				uni.showToast({
					title: res.data.message,
					duration: 2000,
					icon: 'none'
				});
			}
		},
		// 关闭规格库存弹窗
		closeSpecsStockPopup() {
			this.$refs.specsStockPopup.close();
		},
		// 打开调货弹窗
		openTransferPopup(product) {
			this.currentTransfer = {
				product_id: product.id,
				from_shop_id: 0, // 假设0表示从总库存调货
				to_shop_id: '',
				quantity: 0,
				spec_id: '', // 先设为空，fetchSpecs方法会自动设置默认值
				max_quantity: product.total_quantity // 保存商品总库存
			};
			this.fetchSpecs(product.id); // 获取商品的规格列表
			this.fetchStores(); // 获取门店列表
			this.$refs.transferPopup.open();
		},
		updateSpecId(e) {
			if (this.specPickerList.length > 0) {
				const selectedSpec = this.specPickerList[e.detail.value];
				this.currentTransfer.spec_id = selectedSpec.id;
				this.warehouseStock = selectedSpec.warehouse_quantity; // 更新当前规格的库存

			}
		},
		// 更新调入门店ID
		updateDestinationStoreId(e) {
			this.currentTransfer.to_shop_id = this.storePickerList[e.detail.value].id; // 使用门店的索引获取正确的ID
		},

		getStoreName(storeId) {
			const store = this.storePickerList.find(store => store.id === storeId);
			return store ? store.name : '';
		},
		getSpecName(specId) {
			const spec = this.specPickerList.find(spec => spec.id === specId);
			return spec ? spec.spec_name : '';
		},
		async fetchCategories() {
			const res = await this.$myRuquest({
				url: '/index/plugin.stock/getCategories',
				method: 'GET',
				data: {
					main_account_id: this.mainAccountId,
				}
			});
			if (res.data.code === 200) {
				const categories = [{
					id: '',
					name: '请选择分类'
				}, ...res.data.data];
				this.categoryPickerList = this.flattenCategories(categories);
			} else {
				uni.showToast({
					title: res.data.message,
					duration: 2000,
					icon: 'none'
				});
			}
		},
		// 获取规格列表
		async fetchSpecs(productId) {
			const res = await this.$myRuquest({
				url: '/index/plugin.stock/getSpecs',
				method: 'GET',
				data: {
					product_id: productId,
					main_account_id: this.mainAccountId,
				}
			});
			if (res.data.code === 200) {
				this.specPickerList = res.data.data.map(spec => ({
					id: spec.id,
					spec_name: spec.spec_name,
					retail_price: spec.retail_price,
				}));
				// 自动选择第一个规格作为默认值
				if (this.specPickerList.length > 0) {
				this.currentTransfer.spec_id = this.specPickerList[0].id;
				this.warehouseStock = this.specPickerList[0].warehouse_quantity; // 设置初始库存
				console.log(this.warehouseStock)
				}
			} else {
				uni.showToast({
					title: res.data.message,
					duration: 2000,
					icon: 'none'
				});
			}
		},
		getDefaultSpecIndex() {
			if (!this.currentTransfer.spec_id || this.specPickerList.length === 0) return 0;
			const index = this.specPickerList.findIndex(spec => spec.id === this.currentTransfer.spec_id);
			return index >= 0 ? index : 0;
		},

		flattenCategories(categories) {
			let result = [];
			categories.forEach(category => {
				result.push({
					value: String(category.id),
					label: category.name
				});
				if (category.subcategories && category.subcategories.length > 0) {
					const subcategories = category.subcategories.map(sub => ({
						value: String(sub.id),
						label: '--- ' + sub.name
					}));
					result = result.concat(subcategories);
				}
			});
			return result;
		},
		async fetchUnits() {
			const res = await this.$myRuquest({
				url: '/index/plugin.stock/getUnits',
				method: 'GET',
				data: {
					main_account_id: this.mainAccountId,
				}
			});
			if (res.data.code === 200) {
				this.unitPickerList = res.data.data;
			} else {
				uni.showToast({
					title: res.data.message,
					duration: 2000,
					icon: 'none'
				});
			}
		},
		async fetchStores() {
			const res = await this.$myRuquest({
				url: `/index/plugin.stock/getStores`,
				method: 'GET',
				data: {
					user_id: this.mainAccountId,
				}
			});
			if (res.data.code === 200) {
				this.stores = res.data.data;

				this.storePickerList = this.stores.map(store => ({
					id: store.id,
					name: store.name
				}));

			} else {
				uni.showToast({
					title: res.data.message,
					icon: 'none',
					duration: 2000
				});
			}
		},
		getCategoryName(id) {
			const category = this.categoryPickerList.find(cat => cat.value === String(id));
			return category ? category.label : '';
		},
		generateProductId() {
			return Math.random().toString().slice(2, 12);
		},
		getUnitName(unitId) {
			const unit = this.unitPickerList.find(unit => unit.id === parseInt(unitId));
			return unit ? unit.name : '未知单位';
		},
		generateShortCode(product) {
			product.short_code = pinyin.getCamelChars(product.product_name).substring(0, 3).toLowerCase();
		},
		// 获取商品列表
		async fetchProducts() {
		try {
			const res = await this.$myRuquest({
			url: '/index/plugin.stock/getProducts',
			method: 'GET',
			data: {
				searchTerm: this.searchQuery,
				main_account_id: this.userInfo.user_id,
				shop_id: 0,
				page: this.currentPage,    // 当前页码
				pageSize: this.pageSize    // 每页条数
			}
			});
			
			if (res.data.code === 200) {
			this.products = res.data.data; // 商品列表
			this.filteredProducts = [...this.products];
			
			// 更新分页信息
			if (res.data.pagination) {
				this.totalRecords = res.data.pagination.totalRecords;
				this.totalPages = res.data.pagination.totalPages;
				// 保持当前页码同步（后端可能修正页码）
				this.currentPage = res.data.pagination.currentPage;
			}
			}
		} catch (error) {
			console.error('获取商品列表失败:', error);
			uni.showToast({
			title: '加载数据失败',
			icon: 'none'
			});
		}
		},

		// 打开编辑弹窗
		openEdit(product) {
			this.currentProduct = {
				...product
			};
			this.$refs.editPopup.open();
		},

		// 打开新增弹窗
		openAddPopup() {
			this.newProduct = {
				product_code: this.generateProductId(), // 生成随机商品编号
				product_name: '',
				short_code: '',
				retail_price: '',
				product_type: '',
				member_discount: '',
				operator: '',
				category_id: '', // 新增分类字段
				unit_id: '' // 新增单位字段
			};
			this.$refs.addPopup.open();
		},

		// 关闭弹窗
		closePopup() {
			this.$refs.editPopup.close();
			this.$refs.addPopup.close();
			this.$refs.transferPopup.close();
		},

		// 保存商品信息
		async saveProduct() {
			const res = await this.$myRuquest({
				url: '/index/plugin.stock/saveProduct',
				method: 'POST',
				data: {
					main_account_id: this.userInfo.user_id,
					shop_id: this.shopId,
					product_type2: this.items[this.current].value,
					...this.currentProduct,
				}
			});
			if (res.data.code === 200) {
				uni.showToast({
					title: '操作成功',
					icon: 'success',
					duration: 2000
				});
				this.fetchProducts();
				this.closePopup();
			} else {
				uni.showToast({
					title: res.data.message,
					icon: 'none',
					duration: 2000
				});
			}
		},

		async fetchProducts2() {
			const res = await this.$myRuquest({
				url: '/index/plugin.stock/getProducts2',
				method: 'GET',
				data: {
					main_account_id: this.userInfo.user_id,
					shop_id: 0
				}
			});
			if (res.data.code === 200) {
				this.stats = res.data.data.stats; // 从后端获取的统计数据
			} else {
				uni.showToast({
					title: res.data.message,
					duration: 2000,
					icon: 'none'
				});
			}
		},

		// 新增商品
		async addProduct() {
			console.log(this.newProduct);
			const res = await this.$myRuquest({
				url: '/index/plugin.stock/saveProduct',
				method: 'POST',
				data: {
					shop_id: 0,
					product_type2: this.items[this.current].value,
					main_account_id: this.userInfo.user_id,
					...this.newProduct,
				}
			});
			if (res.data.code === 200) {
				uni.showToast({
					title: '操作成功',
					icon: 'success',
					duration: 2000
				});
				this.fetchProducts();
				this.closePopup();
			} else {
				uni.showToast({
					title: res.data.message,
					icon: 'none',
					duration: 2000
				});
			}
		},


		// 处理分页变化
		// handlePageChange(e) {
		// 	this.currentPage = e.detail.current;
		// 	// 根据当前页码来加载不同的数据
		// },
		handlePageChange(e) {
			// 只有页码变化时才重新加载
			if (this.currentPage !== e.current) {
			this.currentPage = e.current;
			this.fetchProducts();
			
			// 滚动到顶部
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 300
			});
			}
		},
  
  // 搜索时重置页码
  filterItems() {
    this.currentPage = 1;
    this.fetchProducts();
  },

		// 打开详情页
		openDetails() {
			console.log('子组件触发全局事件');
			// 使用全局事件总线
			this.$bus.$emit('switch-component', 'ProductDetails');
		},

		// 检查是否登录
		checkLoginStatus() {
			const token = uni.getStorageSync('token');
			if (token) {
				this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
				this.mainAccountId = this.userInfo.user_id;
				this.shopId = this.userInfo.shop_id;
			} else {
				this.userInfo = {};
				this.$router.push('/pages/login/login');
			}
		},

		// 保存调货信息
		async saveTransfer() {
			// 验证调货数量
			if (this.currentTransfer.quantity <= 0) {
				uni.showToast({
				title: '调货数量必须大于0',
				icon: 'none',
				duration: 2000
				});
				return;
			}
			console.log(this.currentTransfer.quantity,this.currentTransfer.max_quantity,this.currentTransfer.quantity> this.currentTransfer.max_quantity);
			
			if (Number(this.currentTransfer.quantity) > Number(this.currentTransfer.max_quantity)) {
				uni.showToast({
				title: `调货数量不能超过总库存(${this.currentTransfer.max_quantity})`,
				icon: 'none',
				duration: 2000
				});
				return;
			}

			// 验证是否选择了门店
			if (!this.currentTransfer.to_shop_id) {
				uni.showToast({
				title: '请选择调入门店',
				icon: 'none',
				duration: 2000
				});
				return;
			}

			// 验证是否选择了规格（如果有规格）
			if (this.specPickerList.length > 0 && !this.currentTransfer.spec_id) {
				uni.showToast({
				title: '请选择规格',
				icon: 'none',
				duration: 2000
				});
				return;
			}
			
			const res = await this.$myRuquest({
				url: '/index/plugin.stock/saveStockTransfer',
				method: 'POST',
				data: {
					main_account_id: this.mainAccountId,
					...this.currentTransfer
				}
			});
			if (res.data.code === 200) {
				uni.showToast({
					title: '调货成功',
					icon: 'success',
					duration: 2000
				});
				this.fetchProducts();
				this.closePopup();
			} else {
				uni.showToast({
					title: res.data.message,
					icon: 'none',
					duration: 2000
				});
			}
		},
		updateNewCategory(e) {
			// 获取选中的分类索引
			const index = e.detail.value;
			// 设置新商品的分类ID
			this.newProduct.category_id = this.categoryPickerList[index].value;
			this.currentProduct.category_id = this.categoryPickerList[index].value;
			
			console.log('已选择分类:', this.getCategoryName(this.newProduct.category_id));
		},
		
		// 确保这个方法也存在
		getCategoryName(id) {
			const category = this.categoryPickerList.find(cat => cat.value === String(id));
			return category ? category.label : '';
		}
	},

	mounted() {
		this.checkLoginStatus();
		this.fetchProducts();
		this.fetchProducts2();
		this.fetchCategories(); // 获取分类列表
		this.fetchUnits(); // 获取单位列表
		this.fetchStores(); // 获取门店列表
	}
};
</script>

<style scoped>
.container {
	padding: 20px;
	background-color: #fff;
}

.popup-container {
	padding: 20px;
	background-color: #fff;
	border-radius: 8px;
}

.form-row {
	display: flex;
	align-items: center;
	margin-bottom: 10px;
}

.button-group {
	display: flex;
	justify-content: space-between;
	margin-top: 20px;
}

.modal-button {
	flex: 1;
	padding: 10px 15px;
	margin: 0 5px;
	background-color: #1abc9c;
	color: #fff;
	border: none;
	border-radius: 4px;
	cursor: pointer;
}

.modal-button.save:hover {
	background-color: #16a085;
}

.modal-button.cancel {
	background-color: #e74c3c;
}

.modal-button.cancel:hover {
	background-color: #c0392b;
}

.stat-cards {
	display: flex;
	flex-wrap: wrap;
	gap: 10px;
	margin-bottom: 20px;
}

.stat-card {
	flex: 1 1 30%;
	display: flex;
	justify-content: space-between;
	align-items: center;
	background-color: #f5f5f5;
	padding: 10px;
	border-radius: 8px;
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	border: 1px solid #ddd;
}

.card-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	flex: 1;
	text-align: center;
}

.divider {
	width: 2px;
	height: 40px;
	background-color: #dcdcdc;
}

.green {
	background-color: #2ecc71;
	color: #fff;
}

.blue {
	background-color: #3498db;
	color: #fff;
}

.orange {
	background-color: #f39c12;
	color: #fff;
}

.controls {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	margin-bottom: 20px;
}

.search-bar {
	flex: 1;
	margin-right: 15px;
}

.control-buttons {
	display: flex;
	flex-wrap: wrap;
	gap: 10px;
}

.control-button {
	padding: 8px 12px;
	background-color: #3498db;
	color: #fff;
	border: none;
	border-radius: 4px;
	cursor: pointer;
}

.control-button:hover {
	background-color: #2980b9;
}

.uni-table {
	width: 100%;
	border-collapse: collapse;
}

.uni-th,
.uni-td {
	padding: 10px;
	border: 1px solid #ddd;
}

.uni-th {
	background-color: #f9f9f9;
}

.member-modal {
	width: 80%;
	max-width: 500px;
	padding: 20px;
	background-color: #fff;
	border-radius: 8px;
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.form-row {
	display: flex;
	align-items: center;
	margin-bottom: 10px;
}

label {
	width: 80px;
	color: #666;
	margin-right: 10px;
}

.input-field {
	flex: 1;
	padding: 8px;
	border: 1px solid #ddd;
	border-radius: 4px;
	outline: none;
}

.button-group {
	display: flex;
	justify-content: space-between;
	margin-top: 20px;
}

.modal-button {
	flex: 1;
	padding: 10px 15px;
	margin: 0 5px;
	background-color: #1abc9c;
	color: #fff;
	border: none;
	border-radius: 4px;
	cursor: pointer;
}

.modal-button.save:hover {
	background-color: #16a085;
}

.modal-button.cancel {
	background-color: #e74c3c;
}

.modal-button.cancel:hover {
	background-color: #c0392b;
}

.specs-table {
	width: 100%;
	max-width: 90vw;
	background: #fff;
	border-radius: 8px;
	padding: 10px;
}

.table-header,
.table-row {
	display: flex;
	border-bottom: 1px solid #eee;
}

.header-cell,
.table-cell {
	flex: 1;
	padding: 8px;
	text-align: center;
}

.table-header {
	font-weight: bold;
	background: #f5f5f5;
}
</style>